<?php

namespace App\Http\Controllers\Api\Activity;

use Illuminate\Support\Facades\DB;

use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\ActivityOrders;
use App\Models\ActivityOrdersCommon;
use App\Models\Banner;
use App\Models\Notice;
use App\Models\OrganizationsMembers;

class ActivityController extends Controller
{
    /**
     * 活动列表
     *
     * @return array
     */
    public function lists(): array
    {

        $organizations_id = request('organizations_id',null);
        $signup_status = request('signup_status',null);
        $key_word = request('key_word',null);
        $start_at = request('start_at',null);
        $end_at = request('end_at',null);

        $where = [];
        if ($organizations_id) {
            $where[] = ['organizations_id','=',$organizations_id];
        }
        if ($signup_status) {
            $where[] = ['status','=',$signup_status];
        }
        if ($key_word) {
            $where[] = ['name','like',"$key_word%"];
        }
        if ($start_at) {
            $where[] = ['start_at','>=',$start_at];
        }
        if ($end_at) {
            $where[] = ['end_at','<=',$end_at];
        }
        if (empty($where)) {
            $where[] = ['id','>',0];
        }
        $field = [
            'id', 
            'name',
            'image',
            'signup_status',
            'status',
            'signup_start_at',
            'signup_end_at',
            'start_at',
            'end_at',
            'detail'
        ];
        $data = Activity::getActivityListByWhere($where,$field);
        // return ret($data);
        $result = array();
        if($data){
            $tmpArr = [];
            foreach ($data as $val){
                // $result[] = Activity::getDataByID($val['id']);
                $month = date('Y年m月',strtotime($val['start_at']));
                $tmpArr[$month][] = Activity::formatListData($val);
            }

            foreach ($tmpArr as $k => $v) {
                $result[] = ['month'=>$k,'list'=>$v];
            }
        }
        return ret($result);
    }

    /**
     * 活动详情
     * @return array
     */
    public function detail(): array
    {
        $id = request('id',null);
        $where = [
            'id'=>$id,
        ];
        $model = Activity::query();
        ModelQuery($id,$model,$where);
        $data = Activity::getDataByID($id);
        if (!empty($data)) {
            unset($data['sort']);
            unset($data['user_id']);
            unset($data['image']);
            unset($data['image_show']);
            unset($data['created_at']);
            unset($data['updated_at']);
        }
        if(!empty($data['detail'])){
            //替换url
            $data['detail'] = str_replace('src="', 'src="https://alumnus.biaoxufilm.com/', $data['detail']);
        }
        $data['is_sign'] = 0;
        //判断是否报名
        $userInfo = auth('api')->user();
        $user_id = $userInfo->id;

        $orderInfo = ActivityOrders::query()->where([
            ['activity_id', '=', $id],
            ['user_id', '=', $user_id]
        ])->first('id as order_id');
        if ($orderInfo['order_id']>0) {
            $aocID = ActivityOrdersCommon::getActivityIdByOrderID($orderInfo['order_id']);
            if ($aocID == $id) {
                $data['is_sign'] = 1;
            }else{
                $data['is_sign'] = 1;
            }
        }

        return ret($data);
    }


    /**
     * 活动报名
     * @return array
     * ALTER TABLE `activity_orders`
ADD COLUMN `activity_id`  int(11) NULL COMMENT '活动ID' AFTER `updated_at`,
ADD COLUMN `applicant_name`  varchar(50) NULL COMMENT '申请人名称' AFTER `activity_id`,
ADD COLUMN `applicant_phone`  varchar(20) NULL COMMENT '申请人手机号' AFTER `applicant_name`;
     */
    public function signUp(): array
    {

        $activity_id = request('activity_id',null);
        $applicant_name = request('applicant_name',null);
        $applicant_phone = request('applicant_phone',null);

        $userInfo = auth('api')->user();
        $activity = Activity::query()->where([
            ['id', '=',$activity_id ]
        ])->first();

        if($activity['remaining_counts'] == 0){
            return retError('报名人数已满');
        }


        $res = ActivityOrders::buildOrder($userInfo,$activity_id,$applicant_name,$applicant_phone);

        if ($res['code'] != 200) {
            return ret($res['data'],$res['code'],$res['msg']);
        }
        unset($res['code']);
        unset($res['msg']);
        return ret($res);
    }

    /**
     * 我的活动列表
     * @return array
     */
    public function myActivity(): array
    {
        $userInfo = auth('api')->user();
        $user_id = $userInfo->id;

        $where = [
           'activity_orders.user_id'=>$user_id
        ];

        $field = [
            'activity.id', 
            'activity.name',
            'activity.image',
            'activity.signup_status',
            'activity.status',
            'activity.signup_start_at',
            'activity.signup_end_at',
            'activity.start_at',
            'activity.end_at',
            'activity.detail'
        ];
        $data = DB::table('activity')
            ->join('activity_orders_common', 'activity_orders_common.activity_id', '=', 'activity.id')
            ->join('activity_orders', 'activity_orders_common.order_id', '=', 'activity_orders.id')
            ->where($where)
            ->distinct('activity.id')
            ->select($field)
            ->get();

        $result = array();
        foreach ($data as $val){
            $result[] = Activity::formatListDataOne($val);
        }

        return ret($result);
    }

    /***
     * @return mixed
     *  申请活动
     */
    public function addActivity() :array
    {

        $post = request()->only('name','image','organizations_id','start_at','end_at','signup_start_at','signup_end_at','price'
        ,'contacts','contact_mobile','detail','total_counts','signup_counts','remaining_counts','ask','local'
        );
        if(empty($post['organizations_id'])){
            return retError('缺少组织ID');
        }

        $user = auth('api')->user();
        $post['user_id'] = $user['id'];
        $post['username'] = $user['username'];


        DB::beginTransaction();
        try {


            $checkAdmin = OrganizationsMembers::query()->where([
                ['organization_id', '=', $post['organizations_id'] ],
                ['is_admin', '=',1],
                ['user_id', '=',$user['id']]
            ])->first();

            if($checkAdmin){
                $post['remaining_counts'] = $post['total_counts'];
                Activity::query()->create($post);
            }else{
                return retError('权限不足');
            }


            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }

    }

}
